import { NgForOfContext } from "@angular/common";
import { HttpClient } from "@angular/common/http";
import { Component, ContentChild, Inject, InjectionToken, Input, OnInit, TemplateRef } from "@angular/core";
import { Observer } from "rxjs";

import { DataRenderColumn, HttpMethod, iWorkflowPagedData, iWorkflowResponse, SearchObject } from "@/app/types/Core";

@Component({
  selector: 'dataRender',
  templateUrl: './index.html'
})
export class DataRenderComponent implements OnInit {

  private loaded: boolean;
  private _pagedDatas: iWorkflowPagedData;

  /** 请求地址 */
  @Input()
  url?: string;

  /** 请求方式 */
  @Input()
  method: HttpMethod = 'post';

  /** 请求参数 */
  @Input()
  so: SearchObject = { CurrentPage: 1, PageSize: 10 } as SearchObject;

  /** 显示列定义 */
  @Input()
  columns: DataRenderColumn[] = [];

  /** 显示数据 */
  @Input()
  datas: Array<any>;

  /** 高度 */
  @Input()
  height: number = 460;

  /** 获取数据 */
  get pagedDatas(): iWorkflowPagedData {
    if (this._pagedDatas) {
      return this._pagedDatas;
    }

    let p = {
      totalCount: 0,
      dataList: this.datas,
    } as iWorkflowPagedData;

    return p;
  };

  /** 子模版（投影） */
  @ContentChild(TemplateRef)
  tpl: TemplateRef<NgForOfContext<any>>;

  /**
   * 构造方法
   * @param http http客户端
   * @param observer 响应对象服务
   */
  constructor (private http: HttpClient, @Inject(DataRenderToken) private observer: Observer<DataRenderChanged>) {
    this.loaded = false;
  }

  /** 组件初始化 */
  ngOnInit(): void {
    this.reSearch();
  }

  /** 重新搜索 */
  reSearch(): void {
    if (this.url && this.method) {
      this.http.request(this.method, this.url, { body: this.so }).subscribe(res => {
        this._pagedDatas = (res as iWorkflowResponse<iWorkflowPagedData>).data;

        if (this.loaded) {
          this.observer.next({ type: 'reload' });
        } else {
          this.loaded = true;
          this.observer.next({ type: 'loaded' });
        }
      });
    }
  }

  /** 页码改变事件处理 */
  pageChanged(pgIndex: number) {
    this.so.CurrentPage = pgIndex;

    this.reSearch();
  }

  /** 每页显示数据大小改变事件处理 */
  pageSizeChanged(pgSize: number) {
    this.so.CurrentPage = 1;
    this.so.PageSize = pgSize;

    this.reSearch();
  }
}

export const DataRenderToken = new InjectionToken('data-render-changed');

export interface DataRenderChanged {
  type: 'loaded' | 'page-changed' | 'reload';
}